package com.example.usharingtest.activities;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.usharingtest.R;

/**
 * Created by X on 2017/9/24.
 */

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.usharingtest.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;


public class WriteArticleActivity extends AppCompatActivity {
    Button sendbutton,cancelbutton;
    ImageButton addpicturebutton,facechoicebutton,takephotobutton;
    EditText userpostedit;
    String choice;
    String content;
    LinearLayout alllinear;
    Uri imageuri;
    final int TAKE_PHOTO=1,CHOOSE_PHOTO=2;
    ImageView photoview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.warticle);
        sendbutton=(Button)findViewById(R.id.sendbutton);
        cancelbutton=(Button)findViewById(R.id.cancelbutton);
        alllinear=(LinearLayout)findViewById(R.id.alllinear);
        facechoicebutton=(ImageButton)findViewById(R.id.facechoicebutton);
        photoview=(ImageView)findViewById(R.id.displayview);
        userpostedit =(EditText)findViewById(R.id.user_postedit);
        alllinear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.linear_eat:
                        Toast.makeText(WriteArticleActivity.this, "1", Toast.LENGTH_LONG).show();
                        break;
                    case R.id.linear_learn:
                        Toast.makeText(WriteArticleActivity.this,"learn",Toast.LENGTH_LONG).show();
                        break;
                    case R.id.linear_tour:
                        Toast.makeText(WriteArticleActivity.this,"tour",Toast.LENGTH_LONG).show();
                        break;
                    default:
                        Toast.makeText(WriteArticleActivity.this,"others",Toast.LENGTH_LONG).show();
                        content="bkcqbwevkqe";
                }
            }
        });
        //
        sendbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = userpostedit.getText().toString();
                String photoPath = "/image/article1";

                SharedPreferences sharedPreferences = getSharedPreferences("userdata",HomepageActivity.MODE_PRIVATE);
                int userid =  sharedPreferences.getInt("userid",-1);
                if(userid == -1){
                    Toast.makeText(WriteArticleActivity.this,"用户未登录发布失败",Toast.LENGTH_SHORT).show();
                }else{
                    postArticle(content,photoPath,userid);
                }
            }
        });
        cancelbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        takephotobutton=(ImageButton)findViewById(R.id.takephotocamera);
        takephotobutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File image=new File(getExternalCacheDir(),"sehun.jpg");
                try{
                    if(image.exists())
                    {image.delete();}
                    image.createNewFile();
                }
                catch (IOException e)
                {e.printStackTrace();}
                if(Build.VERSION.SDK_INT>=24)
                {
                    imageuri= FileProvider.getUriForFile(WriteArticleActivity.this,"com.example.usahringtest.fileprovider",image);
                }
                else {
                    imageuri=Uri.fromFile(image);
                }
                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageuri);
                startActivityForResult(intent,TAKE_PHOTO);
            }

        });
        addpicturebutton=(ImageButton)findViewById(R.id.addpicturebutton);
        addpicturebutton.setOnClickListener(new View.OnClickListener() {
            @Override//从相册中选择照片
            public void onClick(View v) {
                if(ContextCompat.checkSelfPermission(WriteArticleActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(WriteArticleActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }
                else {
                    openAlbum();
                }
            }
        });
        userpostedit=(EditText)findViewById(R.id.user_postedit);
        userpostedit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content=userpostedit.getText().toString();
            }
        });
    }
    private void openAlbum(){
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode)
        {
            case TAKE_PHOTO:
                if(requestCode==RESULT_OK)
                {
                    try{
                        Bitmap bitmap= BitmapFactory.decodeStream(getContentResolver().openInputStream(imageuri));
                        photoview.setImageBitmap(bitmap);
                    }
                    catch (FileNotFoundException e)
                    {e.printStackTrace();}
                }
                break;
            case CHOOSE_PHOTO:
                if(resultCode==RESULT_OK){
                    if(Build.VERSION.SDK_INT>=19)
                    {handImageOnKitKat(data);}
                    else {
                        handImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handImageOnKitKat(Intent data){
        String imagepath=null;
        Uri uri=data.getData();
        if(DocumentsContract.isDocumentUri(this,uri))
        {
            String docid=DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority()))
            {
                String id=docid.split(":")[1];
                String selection=MediaStore.Images.Media._ID+"="+id;
                imagepath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }
            else if("com.android.providers.downloads.documents".equals(uri.getAuthority()))
            {
                Uri contenturi= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docid));
                imagepath=getImagePath(contenturi,null);
            }
            else if("content".equalsIgnoreCase(uri.getScheme()))
            {
                imagepath=getImagePath(uri,null);
            }
            else if("file".equalsIgnoreCase(uri.getScheme()))
            {   imagepath=uri.getPath();}
            displayImage(imagepath);
        }
    }
    private void handImageBeforeKitKat(Intent data)
    {
        Uri uri=data.getData();
        String imagepath=getImagePath(uri,null);
        displayImage(imagepath);
    }
    private String getImagePath(Uri uri,String selection)
    {
        String path=null;
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null)
        {
            if(cursor.moveToFirst())
            {
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    private void displayImage(String imagepath)
    {
        if(imagepath!=null)
        {
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            photoview.setImageBitmap(bitmap);
        }
        else {
            Toast.makeText(WriteArticleActivity.this,"failed",Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode)
        {
            case 1:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
                {openAlbum();}
                else{
                    Toast.makeText(WriteArticleActivity.this,"failed",Toast.LENGTH_LONG).show();;
                }
                break;
            default:break;
        }
    }

    public void postArticle(String content,String photopath, int userid){

    }

}
